import { request } from '../../request/index.js';
import regeneratorRuntime from '../../lib/runtime/runtime'
// pages/category/category.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 左边大菜单数据```
    leftMenuList: [],
    // 右边商品列表数据
    rightContent: [],

    currentIndex:0,
    scrollTop:0
  },

  // 接口返回的数据
  Cates: [],

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    const Cates = wx.getStorageSync('cates')
    // 如果，没有数据，重新发送请求
    if(!Cates){
          this.getCates();
    }else {
      // 有数据，判断是否已经过期
      if(Date.now() - Cates.time > 1000 * 600){
        this.getCates();
      }else {
        // 使用已有数据
        this.Cates = Cates.data;
        let leftMenuList = this.Cates.map((v) => v.cat_name);
        let rightContent = this.Cates[0].children;
        this.setData({
          leftMenuList,
          rightContent,
        });
      }
    }
  },

  async getCates() {

    const res = await request({url:'/categories'});
      this.Cates = res;
      
      //请求数据得到的数据存储在本地
      wx.setStorageSync('cates', {time:Date.now(),data:this.Cates})

      let leftMenuList = this.Cates.map((v) => v.cat_name);

      let rightContent = this.Cates[0].children;
      this.setData({
        leftMenuList,
        rightContent,
      });
  },

  handelTabChange(e) {
    const {index} = e.currentTarget.dataset

    let rightContent = this.Cates[index].children;

    this.setData({
      currentIndex:index,
      rightContent,
      scrollTop:0
    })
    
  },

});
